﻿//定义全局变量是否单选
var sfdx = false;


$(function () {
    $.ajaxSetup({
        contentType: "application/x-www-form-urlencoded;charset=utf-8",
        error: function (jqXHR, exception) {
            if (jqXHR.status === 0) {
                //alert('系统无法连接,请验证网络。');
            } else if (jqXHR.status == 404) {
                // alert('请求的页面没有找到[404]。');
            } else if (jqXHR.status == 500) {
                // alert('服务器内部错误[500]。');
            } else if (exception === 'parsererror') {
                // alert('请求JSON解析失败。');
            } else if (exception === 'timeout') {
                // alert('超时错误。');
            } else if (exception === 'abort') {
                // alert('Ajax请求中止。');
            } else {
                // alert('未捕获的错误。\n' + jqXHR.responseText);
            }
        },
        complete: function (XMLHttpRequest, textStatus) {
//            alert(XMLHttpRequest.responseText);
            var sessionTimeOut = XMLHttpRequest.getResponseHeader("sessionstatus");
            if (sessionTimeOut == "timeout") {
                var timeInterval;
                var winContainner = $($('<div style="padding: 10px;font: 12px">登陆超时<span class="second" style="font: 15px red;margin: 0 5px;"></span>后跳转登陆页面</div>').appendTo('body'));
                var win = winContainner.dialog({
                    title: "登陆超时",
                    collapsible: false,
                    minimizable: false,
                    maximizable: false,
//                    closable:false,
                    modal: true,
                    width: 185,
                    height: 100,
                    noheader: true,
                    buttons: [
                        {
                            text: '确定',
                            handler: function () {
                                $(win).window("close");
                                clearInterval(timeInterval);
                                window.location.href = $.webPath() + "/portal/login";
                            }
                        }/*,{
                         text:'返回',
                         handler:function(){
                         $(win).window("close");
                         clearInterval(timeInterval);
                         }
                         }*/
                    ],
                    onOpen: function () {
                        var second = 5;
                        timeInterval = setInterval(function () {
                            if (second >= 0) {
                                $(win).find("span.second").text(second);
                                --second;
                            } else {
                                $(win).window("close");
                                clearInterval(timeInterval);
                                window.location.href = $.webPath() + "/portal/login";
                            }
                        }, 1000);
                    }
                });
            }
        }
    });

    function convertMenu(rows) {
        function exists(rows, parentId) {
            for (var i = 0; i < rows.length; i++) {
                if (rows[i].id == parentId) return true;
            }
            return false;
        }

        var nodes = [];
        // 得到顶层节点
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            if (!exists(rows, row.parentId)) {
                nodes.push({
                    id: row.id,
                    text: row.text,
                    state: 'closed',
                    attributes: {parentId: row.parentId,type: row.type}
                });
            }
        }
        var toDo = [];
        for (var i = 0; i < nodes.length; i++) {
            toDo.push(nodes[i]);
        }
        while (toDo.length) {
            var node = toDo.shift();    // 父节点
            // 得到子节点
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                if (row.parentId == node.id) {
                    var child;
                    if (row.url)
                        child = {id: row.id, state: row.state, text: row.text, attributes: {url: row.url, parentId: row.parentId,type: row.type}};
                    else
                        child = {id: row.id, state: 'closed', text: row.text, attributes: {parentId: row.parentId,type: row.type}};
                    if (node.children) {
                        node.children.push(child);
                    } else {
                        node.children = [child];
                    }
                    toDo.push(child);
                }
            }
        }
        return nodes;
    }
    //$(".easyui-layout :first .layout-button-left :first").removeClass('panel-tool a').addClass('small');

    //实例化树形菜单
    $("[name='menuTree']").tree({
        url: $.webPath() + '/main/createMenu',
        animate: true,
        lines: false,
        loadFilter: function (rows) {
            return convertMenu(rows);
        },
        onSelect: function (node) {
            if (node.attributes.url) {
                open(node.text, node.attributes.url, node.attributes.type);
            } else {
                $(this).tree("toggle", node.target);
            }
        }
    });
    //在右边center区域打开菜单，新增tab
    function open(text, url, type) {
        if ($("#tabs").tabs('exists', text)) {
            $('#tabs').tabs('select', text);
            $('#tabs').tabs('getSelected').panel("refresh");
        } else if (type == 'bbtj') {
            $('#tabs').tabs('add', {
                title: text,
                cache: true,
                closable: true,
                content: '<iframe scrolling="no" frameborder="0" src="' + $.webPath() + '/' + url + '" style="width:100%;height:100%;"></iframe>'
                //href: '../' + url
            });
        } else {
            $('#tabs').tabs('add', {
                title: text,
                cache: true,
                closable: true,
//                content: '<iframe scrolling="no" frameborder="0" src="../'+url+'" style="width:100%;height:100%;"></iframe>'
                href: $.webPath() + '/' + url
            });
        }
    }


    //绑定tabs的右键菜单
    $("#tabs").tabs({
        onContextMenu: function (e, title) {
            e.preventDefault();
            $('#tabsMenu').menu('show', {
                left: e.pageX,
                top: e.pageY
            }).data("tabTitle", title);
        }
    });

    //实例化menu的onClick事件
    $("#tabsMenu").menu({
        onClick: function (item) {
            closeTab(this, item.name);
        }
    });


    //几个关闭事件的实现
    function closeTab(menu, type) {
        var curTabTitle = $(menu).data("tabTitle");
        var tabs = $("#tabs");

        if (type === "close") {
            tabs.tabs("close", curTabTitle);
            return;
        }

        if (type === "refresh") {
            tabs.tabs('select', curTabTitle);
            tabs.tabs('getSelected').panel("refresh");
            return;
        }
        var allTabs = tabs.tabs("tabs");
        var closeTabsTitle = [];

        $.each(allTabs, function () {
            var opt = $(this).panel("options");
            if (opt.closable && opt.title != curTabTitle && type === "other") {
                closeTabsTitle.push(opt.title);
            } else if (opt.closable && type === "all") {
                closeTabsTitle.push(opt.title);
            }
        });

        for (var i = 0; i < closeTabsTitle.length; i++) {
            tabs.tabs("close", closeTabsTitle[i]);
        }
    }

    //查询框收缩
    $('.sea-tool').live("click", function () {
        $(this).toggle(function () {
                $(this).parent(".PTools").next(".textcon").hide();
                //$('.textcon').hide();
                $(this).parents(".easyui-layout").layout("resize");
            },
            function () {
                $(this).parent(".PTools").next(".textcon").show();
                //$('.textcon').show();
                $(this).parents(".easyui-layout").layout("resize");
            }).trigger('click');
    });

    //下拉框获得焦点是展示下拉框

    $('span.combo').find('input.combo-text').live('focus', function () {
        if (!$(this).parent().prev().combo("options").readonly) {
            if (!$(this).parent().prev().combo("getValue"))
                $(this).parent().prev().combo("showPanel");
        }
    });

    //为所有查询输入框绑定Enter事件
    $('div.textcon .input-text,div.textcon .input-text').live("keypress", function (e) {
        if (e.which == 13) {
            $(e.target).closest('div.textcon').find(".submit").click();
        }
    });

    //自定义校验
    if ($.fn.validatebox) {
        $.extend($.fn.validatebox.defaults.rules, {
            remote: { //自定义远程校验
                validator: function (value, param) {
                    var returnType = false;
                    $.ajax({
                        url: param[0],
                        type: 'post',
                        data: $.extend({'validateVal': value}, param[1]),
                        async: false,
                        cache: false,
                        dataType: 'json',
                        success: function (data) {
                            returnType = data.valid;
                            //销售单选择库存零售客户远程验证进行按钮字样的切换
                            changeBtnLksh(data, param);
                        }
                    });
                    return returnType;
                },
                message: '{2}'
            },
            fixLength: { //定长校验
                validator: function (value, param) {
                    return value.length == param[0];
                },
                message: '该字段必须输入{0}个字符！'
            },
            maxLength: {
                validator: function (value, param) {
                    return value.length <= param[0];
                },
                message: '长度不能超过{0}位'
            },
            min: {
                validator: function (value, param) {
                    return value > param[0];
                },
                message: "{1}必须大于{0}"
            },
            //路径上下游验证
            syxy: {
                validator: function (value, param) {
                    return !(value.split(",").length > 1 &&
                        $(param[0]).combobox("getText").split(",").length > 1);
                },
                message: "{1}"
            },
            formatPhone: { //定长校验
                validator: function (value, param) {
                    return value.match(/^1[3|4|5|8][0-9]\d{4,8}$/);
                },
                message: '你输入的手机格式不正确！'
            },
            //验证逗号
            numberDh: {
                validator: function (value, param) {
                    return /^[0-9]{0}([0-9]|[.])+$/.test(value);
                },
                message: '充值金额输入有误！'
            }
        });
    }

    //自定义下拉框全匹配
    if ($.fn.combobox) {
        $.extend($.fn.combobox.defaults, {
            filter: function (q, row) {
                var opts = $(this).combobox('options');
                return row[opts.textField].indexOf(q) != -1;
            }
        });
    }

    if ($.fn.combogrid) {
        $.extend($.fn.combogrid.defaults, {
            filter: function (q, row) {
                var opts = $(this).combogrid('options');
                return row[opts.textField].indexOf(q) != -1;
            }
        });
    }

    $("input[readOnly='readOnly']").live('keydown', function (e) {
        e.preventDefault();
    });

    //document.onkeydown();
    $(document).live('keydown', function (e) {
        var key = e.which || e.keyCode;
        if (key == 8) {
            var srcElement = e.srcElement || e.target;
            if (srcElement.tagName.toUpperCase() != "INPUT"
                && srcElement.tagName.toUpperCase() != "TEXTAREA"
                && srcElement.tagName.toUpperCase() != "TEXT") {
                e.preventDefault();
            }
        }
    })

    $(window).live('keydown', function (e) {
        var key = e.which || e.keyCode;
        if (key == 8) {
            var srcElement = e.srcElement || e.target;
            if (srcElement.tagName.toUpperCase() != "INPUT"
                && srcElement.tagName.toUpperCase() != "TEXTAREA"
                && srcElement.tagName.toUpperCase() != "TEXT") {
                e.preventDefault();
            }
        }
    })

    $("#yg_view").click(function () {
        PersonnelYgDialog("员工个人信息");
    });


    //菜单栏样式调整
    $(".panel-title").removeClass('panel-title').addClass('panel-title2');
    $(".panel-title2").text('菜单栏');
    $(".panel-tool").addClass('brothers');

});
//弹出员工个人信息
function PersonnelYgDialog(title) {
    var href = $.webPath() + "/sys/yg/yg_view_content";
    showYgViewDialog(title, href);
}

function showYgViewDialog(title, href) {
    var win = $.window({
        onBeforeClose: function () {
            $(".validatebox-tip").remove();
        },
        title: title,
        width: 550,
        height: 390,
        cache: false,
        url: href,
        modal: true
    });
}

function readOnly(obj) {
    if (obj) {
        if (obj.attr('comboname')) {
            obj.next("span").children("span").children("span").attr('disabled', 'disabled');
            obj.next("span").children("input").attr('readOnly', 'readOnly');
        } else {
            obj.attr('readOnly', 'readOnly');
        }
    }
}

function editOnly(obj) {
    if (obj) {
        if (obj.attr('comboname')) {
            obj.next("span").children("span").children("span").removeAttr('disabled');
            obj.next("span").children("input").removeAttr('readOnly');
        } else {
            obj.removeAttr('readOnly');
        }
    }
}

function destroy(id) {
    $('#' + id).uploadify('destroy');
}

function openwindow(url) {
    window.open(url, '论坛', 'width=' + (window.screen.availWidth - 10) + ',height=' + (window.screen.availHeight - 30) + ',top=0,left=0,resizable=yes,status=yes,menubar=no,scrollbars=yes');
}



function watchBmfw(){
    var win = $.window({
        title: "查看编码",
        iconCls: 'icon-tip',
        url: $.webPath() + "/sys/wzbm/search_wzbm_yg",
        width: 1000,
        height: 600,
        modal: true,
        isMax: false
    });
}

function modifyYgPassword() {
    var win = $.window({
        title: "修改密码",
        iconCls: 'icon-mdl',
        url: $.webPath() + "/sys/yg/tomodifyYgPassword",
        width: 330,
        height: 200,
        iconCls: 'icon-edit',
        modal: true,
        isMax: false,
        buttons: [
            {
                text: '确认',
                handler: function () {
                    $(win).mask();
                    $('#ModifyPassword').form('submit', {
                        onSubmit: function (param) {
                            var data1 = $("#newPwd").val();
                            var data2 = $("#newPwd2").val();
                            var oldpwd = $("#oldPwd").val();
                            if (oldpwd == data1) {
                                $(win).mask('hide');
                                $.messager.alert('提示', '修改的密码不可重复', 'error');
                                return false;
                            }
                            if (data1 != data2) {
                                $(win).mask('hide');
                                $.messager.alert('提示', '两次输入的密码需要一致', 'error');
                                return false;
                            }
                        },
                        success: function (data) {
                            $(win).mask('hide');
//                            var json = $.parseJSON(data);
//                            if (data.statusCode == 200) {
                            if (data == '修改密码成功') {
                                $(win).window('close');
                                $.messager.show({
                                    title: '提示',
                                    msg: data,
                                    timeout: 3000,
                                    showType: 'slide'
                                });
                            } else
                                $.messager.alert('提示', data, 'error');
                        }
                    });
                }
            }
        ]
    });
}
//格式化利率
function formatLl(num) {
    if (!num || num == null)
        return 0.0000;
    num = Math.round(num * Math.pow(10, 4)) / Math.pow(10, 4)
    return formatnumber(num, 4);
}
//格式化金额
function formatMoney(num) {
    if (!num || num == null)
        return 0.00;
    num = Math.round(num * Math.pow(10, 2)) / Math.pow(10, 2)
    return formatnumber(num, 2);
}

function formatMoneyFourWei(num) {
    if (!num || num == null)
        return 0.0000;
    num = Math.round(num * Math.pow(10, 4)) / Math.pow(10, 4)
    return formatnumber(num, 4);
}

function multiply(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length
    } catch (e) {
    }
    try {
        m += s2.split(".")[1].length
    } catch (e) {
    }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}

/**
 * 格式化数量
 * @param num 被格式化的数字
 * @param groupSeparator 这个字符分割整数组,显示成千上百万的时候.
 * @param decimalSeparator 小数分隔符分割整数和小数部分的数字.
 * @param prefix 前缀字符串.
 * @param suffix 后缀字符串.
 * @return {*}
 */
function formatSl(num, groupSeparator, decimalSeparator, prefix, suffix) {
    if (isNaN(num)) {
        return num;
    }
    if (!num) {
        num = 0.000;
    }
    num = Math.round(num * Math.pow(10, 3)) / Math.pow(10, 3);
    if (!prefix) prefix = "";
    if (!decimalSeparator) decimalSeparator = ".";
    if (!suffix) suffix = "";
    num = num + "";
    var s1 = num, s2 = "";
    var idx = num.indexOf(".");
    if (idx >= 0) {
        s1 = num.substring(0, idx);
        s2 = num.substring(idx + 1, num.length);
    }
    if (groupSeparator) {
        var p = /(\d+)(\d{3})/;
        while (p.test(s1)) {
            s1 = s1.replace(p, "$1" + groupSeparator + "$2");
        }
    }
    if (s2) {
        return formatnumber((prefix + s1 + decimalSeparator + s2 + suffix), 3);
    } else {
        return formatnumber((prefix + s1 + suffix), 3);
    }
}

function formatSl2(num, groupSeparator, decimalSeparator, prefix, suffix) {
    if (isNaN(num)) {
        return num;
    }

    if (!num) {
        num = 0.00;
    }
    num = Math.round(num * Math.pow(10, 2)) / Math.pow(10, 2);
    if (!prefix) prefix = "";
    if (!decimalSeparator) decimalSeparator = ".";
    if (!suffix) suffix = "";
    num = num + "";
    var s1 = num, s2 = "";
    var idx = num.indexOf(".");
    if (idx >= 0) {
        s1 = num.substring(0, idx);
        s2 = num.substring(idx + 1, num.length);
    }
    if (groupSeparator) {
        var p = /(\d+)(\d{3})/;
        while (p.test(s1)) {
            s1 = s1.replace(p, "$1" + groupSeparator + "$2");
        }
    }
    if (s2) {
        return formatnumber((prefix + s1 + decimalSeparator + s2 + suffix), 2);
    } else {
        return formatnumber((prefix + s1 + suffix), 2);
    }
}

function formatSlForHtml(v, r, i) {
    return formatSl(v, ",");
}

function formatSlForHtml2(v, r, i) {
    return formatSl2(v, ",");
}

function seBeiFormatter(value) {
    if (value == 'sb') {
        return "设备";
    }
    if (value == "cl") {
        return "材料";
    }
}

//格式化金额（千分位，并且保存两位小数）
function formatJe2(num, groupSeparator, decimalSeparator, prefix, suffix) {
    if (isNaN(num)) {
        return num;
    }
    if (!num) {
        num = 0.00;
    }
    num = Math.round(num * Math.pow(10, 2)) / Math.pow(10, 2);
    if (!prefix) prefix = "";
    if (!decimalSeparator) decimalSeparator = ".";
    if (!suffix) suffix = "";
    num = num + "";
    var s1 = num, s2 = "";
    var idx = num.indexOf(".");
    if (idx >= 0) {
        s1 = num.substring(0, idx);
        s2 = num.substring(idx + 1, num.length);
    }
    if (groupSeparator) {
        var p = /(\d+)(\d{3})/;
        while (p.test(s1)) {
            s1 = s1.replace(p, "$1" + groupSeparator + "$2");
        }
    }
    if (s2) {
        return formatnumber((prefix + s1 + decimalSeparator + s2 + suffix), 2);
    } else {
        return formatnumber((prefix + s1 + suffix), 2);
    }
}

//格式化金额（千分位，并且保存两位小数）
function formatJe(num, groupSeparator, decimalSeparator, prefix, suffix) {
    if (isNaN(num)) {
        return num;
    }

    if (!num) {
        num = 0.0000;
    }
    num = Math.round(num * Math.pow(10, 4)) / Math.pow(10, 4);
    if (!prefix) prefix = "";
    if (!decimalSeparator) decimalSeparator = ".";
    if (!suffix) suffix = "";
    num = num + "";
    var s1 = num, s2 = "";
    var idx = num.indexOf(".");
    if (idx >= 0) {
        s1 = num.substring(0, idx);
        s2 = num.substring(idx + 1, num.length);
    }
    if (groupSeparator) {
        var p = /(\d+)(\d{3})/;
        while (p.test(s1)) {
            s1 = s1.replace(p, "$1" + groupSeparator + "$2");
        }
    }
    if (s2) {
        return formatnumber((prefix + s1 + decimalSeparator + s2 + suffix), 4);
    } else {
        return formatnumber((prefix + s1 + suffix), 4);
    }
}

function formatJeForHtml(v, r, i) {
    return formatJe(v, ",");
}

function formatJeForHtml2(v, r, i) {
    return formatJe2(v, ",");
}

function formatnumber(value, num) {
    var a, b, c, i;
    a = value.toString();
    b = a.indexOf(".");
    c = a.length;
    if (num == 0) {
        if (b != -1) {
            a = a.substring(0, b);
        }
    } else {
        if (b == -1) {
            a = a + ".";
            for (i = 1; i <= num; i++) {
                a = a + "0";
            }
        } else {
            a = a.substring(0, b + num + 1);
            for (i = c; i <= b + num; i++) {
                a = a + "0";
            }
        }
    }
    return a;
}


//到期日提醒  sysDate 系统时间  dqrDate 到期日期  txsj 设定的多少天提醒
function formatDate(sysDate, dqrDate, txsj) {
    if (dqrDate) {
        var sysdate = new Date(Date.parse(sysDate.replace(/-/g, "/")));
        var dqrdate = new Date(Date.parse(dqrDate.replace(/-/g, "/")));
        var time = dqrdate.getTime() - sysdate.getTime();
        if (time < 0 || parseInt(time / (1000 * 60 * 60 * 24)) < txsj) {
            return '<div style="color: red">' + dqrDate + '<div>';
        } else {
            return dqrDate;
        }
    }
    return dqrDate;
}
//判断零售客户的导入按钮的状态
function changeBtnLksh(data, param) {
    if (data.valid == false) {
        if (param[1].validateField == "qc") {
            $("#lskh_qcTool").css('display', 'block');
            $("#lskh_qyfrhTool").css('display', 'none');
            $("#lskh_zzjghTool").css('display', 'none');
            $("#lskh_nshTool").css('display', 'none');
        } else if (param[1].validateField == "qyfrh") {
            $("#lskh_qyfrhTool").css('display', 'block');
            $("#lskh_zzjghTool").css('display', 'none');
            $("#lskh_nshTool").css('display', 'none');
            $("#lskh_qcTool").css('display', 'none');
        } else if (param[1].validateField == "zzjgh") {
            $("#lskh_zzjghTool").css('display', 'block');
            $("#lskh_nshTool").css('display', 'none');
            $("#lskh_qcTool").css('display', 'none');
            $("#lskh_qyfrhTool").css('display', 'none');
        } else if (param[1].validateField == "nsh") {
            $("#lskh_nshTool").css('display', 'block');
            $("#lskh_qcTool").css('display', 'none');
            $("#lskh_qyfrhTool").css('display', 'none');
            $("#lskh_zzjghTool").css('display', 'none');
        }
    } else {
        $("#lskh_qcTool").css('display', 'none');
        $("#lskh_qyfrhTool").css('display', 'none');
        $("#lskh_zzjghTool").css('display', 'none');
        $("#lskh_nshTool").css('display', 'none');
    }
}


